package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.CartItem;
import java.util.Iterator;
import org.csu.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class UpdateCartQuantitiesServlet extends HttpServlet {
    //处理请求完后的页面
    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";

    //定义处理请求所需要的数据
    private Cart cart;
    private Iterator<CartItem> cartItems;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        cart = (Cart)session.getAttribute("cart");

        cartItems = cart.getAllCartItems();
        while(cartItems.hasNext()){
            CartItem cartItem = cartItems.next();
            String itemId = cartItem.getItem().getItemId();
            try{
                int quantity = Integer.parseInt(req.getParameter(itemId));
                cart.setQuantityByItemId(itemId,quantity);
                if(quantity<1){
                    cartItems.remove();
                }

            }catch (Exception e){
                e.printStackTrace();
            }
        }
        session.setAttribute("cart",cart);
        req.getRequestDispatcher(VIEW_CART).forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
